﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using JStore.Core.Commands;
using JStore.Core.Dtos;
using JStore.Core.Entities;
using JStore.Core.Enums;
using JStore.Tasks;
using JStore.Web.Controllers.Users.ViewModels;
using Newtonsoft.Json;
using SpeadFrm.Extensions;
using SpeadFrm.Mappers;
using SpeadFrm.MvcPager;
using SpeadFrm.Utility;

namespace JStore.Web.Controllers.Users
{
    public class UsersController : BaseController
    {
        private readonly UserPasswordTask _userPasswordTask = new UserPasswordTask();
        private readonly CardTypeTask _cardTypeTask = new CardTypeTask();
        private readonly UserInfoTask _userInfoTask = new UserInfoTask();
        private readonly UserTypeTask _userTypeTask = new UserTypeTask();
        private readonly CompanyMoneyLogTask _companyMoneyLogTask = new CompanyMoneyLogTask();

        public ActionResult ChangePassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                var userPassword = _userPasswordTask.GetByUserName(LogOnUserName);
                if (userPassword.Password != CryptTools.HashPassword(model.OldPassword))
                    return AlertMsg("登录密码不正确", Request.UrlReferrer.PathAndQuery);

                userPassword.Password = CryptTools.HashPassword(model.NewPassword);
                _userPasswordTask.Update(userPassword);
                return AlertMsg("修改密码成功", Request.UrlReferrer.PathAndQuery);
            }
            return View(model);
        }

        public ActionResult Register()
        {
            ViewData["CardClassList"] = CardClass.Member.ToSelectList();
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                var cmd = EntityMapper.Map<RegisterModel, RegisterCmd>(model);
                var errMsg = string.Empty;
                var userId = 0;
                if (_userInfoTask.Register(cmd,LogOnUserName, out errMsg, out userId))
                {
                    return RedirectToAction("RegSuccess", "Users", new { userId = userId });
                }
                else
                    return AlertMsg("注册失败:" + errMsg, Request.UrlReferrer.PathAndQuery);
            }

            return AlertMsg("参数异常", Request.UrlReferrer.PathAndQuery);
        }

        public ActionResult UserDetail(string userName)
        {
            var userInfo = _userInfoTask.GetByUserName(userName);
            if (userInfo == null) return Content("会员信息不存在");

            var model = EntityMapper.Map<UserInfo, UserInfoModel>(userInfo);
            var cardType = _cardTypeTask.GetById(userInfo.CardType);
            var userType = _userTypeTask.GetById(userInfo.UserTypeId);
            model.CardTypeName = cardType.CardName;
            model.UserTypeName = userType.UserTypeName;
            return View(model);
        }

        public ActionResult RegSuccess(int userId)
        {
            var userInfo = _userInfoTask.GetByUserId(userId);
            if (userInfo == null) return Content("参数异常");
            var userInfoModel = EntityMapper.Map<UserInfo, UserInfoModel>(userInfo);
            return View(userInfoModel);
        }

        public ActionResult List(string userName, string jdUserName, string tjUserName, int? userTypeId, string areaUserName, bool? isArea, int pageIndex = 1, int pageSize = 10)
        {
            var userTypeList = _userTypeTask.GetAll().ToSelectList(c => c.Id.ToString(), c => c.UserTypeName);
            userTypeList.Insert(0, new SelectListItem { Text = "全部", Value = string.Empty });
            ViewData["UserTypeList"] = userTypeList;

            ViewData["IsAreaList"] = new List<SelectListItem>
                                         {
                                             new SelectListItem {Text = "全部", Value = string.Empty, Selected = true},
                                             new SelectListItem {Text = "是", Value = "True"},
                                             new SelectListItem {Text = "否", Value = "False"},
                                         };

            var pagedList = _userInfoTask.GetPagedList(userName, jdUserName, tjUserName, userTypeId, areaUserName, isArea, pageIndex, pageSize);
            var items = pagedList.Select(EntityMapper.Map<UserInfoDto, UserInfoModel>).ToList();
            var model = new PagedList<UserInfoModel>(items, pageIndex, pageSize, pagedList.TotalItemCount);
            return View(model);
        }

        public ActionResult TjTree(string userName)
        {
            var userInfo = _userInfoTask.GetByUserName(userName);
            var list = _userInfoTask.GetTjTreeList(userName, 2);

            var treeList = list.Select(c => new ZTreeModel
                                                {
                                                    id = c.UserId,
                                                    pId = (int)c.TjUserId,
                                                    name = c.UserName,
                                                    open = true,
                                                    url = Url.Action("UserDetail", "Users", new { c.UserName }),
                                                    target = "userDetail",
                                                }).ToList();
            treeList.Insert(0, new ZTreeModel
                                   {
                                       id = userInfo.UserId,
                                       pId = 0,
                                       name = userInfo.UserName,
                                       open = true,
                                       url = Url.Action("UserDetail", "Users", new { userInfo.UserName }),
                                       target = "userDetail",
                                   });
            ViewData["jsonData"] = JsonConvert.SerializeObject(treeList);
            return View("TjTree");
        }

        public ActionResult UserTjTree()
        {
            return TjTree(LogOnUserName);
        }

        public ActionResult UserJdTree()
        {
            return JdTree(LogOnUserName);
        }

        public ActionResult EditUser()
        {
            var userInfo = _userInfoTask.GetByUserName(LogOnUserName);
            var model = EntityMapper.Map<UserInfo, UserInfoModel>(userInfo);
            var cardType = _cardTypeTask.GetById(userInfo.CardType);
            var userType = _userTypeTask.GetById(userInfo.UserTypeId);
            model.CardTypeName = cardType.CardName;
            model.UserTypeName = userType.UserTypeName;
            ViewData["UserModel"] = model;
            return View();
        }

        [HttpPost]
        public ActionResult EditUser(string name, string phone, string mobile, string address)
        {
            var userInfo = _userInfoTask.GetByUserName(LogOnUserName);
            userInfo.Name = name;
            userInfo.Phone = phone;
            userInfo.Mobile = mobile;
            userInfo.Address = address;
            _userInfoTask.Update(userInfo);
            return AlertMsg("修改成功", Request.UrlReferrer.PathAndQuery);
        }

        public ActionResult JdTree(string userName)
        {
            var userInfo = _userInfoTask.GetByUserName(userName);
            var list = _userInfoTask.GetJdTreeList(userName, 2);
            var treeList = list.Select(c => new ZTreeModel
            {
                id = c.UserId,
                pId = (int)c.JdUserId,
                name = c.UserName,
                open = true,
                url = Url.Action("UserDetail", "Users", new { c.UserName }),
                target = "userDetail",
            }).ToList();
            treeList.Insert(0, new ZTreeModel
            {
                id = userInfo.UserId,
                pId = 0,
                name = userInfo.UserName,
                open = true,
                url = Url.Action("UserDetail", "Users", new { userInfo.UserName }),
                target = "userDetail",
            });
            ViewData["jsonData"] = JsonConvert.SerializeObject(treeList);
            return View("JdTree");
        }

        public ActionResult Update1()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Update1(string userName)
        {
            return RedirectToAction("Update", "Users", new { userName });
        }

        public ActionResult Update(string userName)
        {
            if (string.IsNullOrEmpty(userName))
                return Content("参数异常");

            string errMsg;
            if (!_userInfoTask.CanUpdate(userName, out errMsg))
                return Content(errMsg);

            var userInfo = _userInfoTask.GetByUserName(userName);
            var cardTypeList = _cardTypeTask.GetUpdateUserTypeList(userInfo.UserTypeId, userInfo.CardClass);
            var userTypeList = _userTypeTask.GetByIds(cardTypeList.Select(c => c.UserTypeId).ToList())
                .ToSelectList(c => c.Id.ToString(), c => c.UserTypeName);
            ViewData["UserTypeList"] = userTypeList;
            var model = new UserUpdateModel { UserName = userName };
            return View(model);
        }

        [HttpPost]
        public ActionResult Update(UserUpdateModel model)
        {
            if (ModelState.IsValid)
            {
                string errMsg;
                return _userInfoTask.Upgrade(model.UserName, model.UserTypeId, model.RealMoney,LogOnUserName, out errMsg)
                           ? AlertMsg("会员升级成功", Url.Action("Update1", "Users"))
                           : AlertMsg(errMsg, Request.UrlReferrer.PathAndQuery);
            }
            return AlertMsg("参数异常", Request.UrlReferrer.PathAndQuery);
        }

        public ActionResult GetCardTypes(int cardClass)
        {
            var model = _cardTypeTask.GetListByCardClass(cardClass)
                .ToSelectList(c => c.Id.ToString(), c => c.CardName);
            return Json(model, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetJoinMoney(int cardType)
        {
            var info = _cardTypeTask.GetById(cardType);
            var model = info == null
                            ? null
                            : new
                                  {
                                      info.Price,
                                      info.SaleRate,
                                  };
            return Json(model, JsonRequestBehavior.AllowGet);
        }

        public ActionResult CanTj(string userName)
        {
            var canTj = _userInfoTask.CanTj(userName);
            return Json(canTj, JsonRequestBehavior.AllowGet);
        }

        public ActionResult CanJd(string userName)
        {
            string errMsg;
            var canJd = _userInfoTask.CanJd(userName, out errMsg);
            return Json(new { result = canJd, msg = errMsg }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetJdSortList(string userName)
        {
            var list = _userInfoTask.GetJdSortList(userName)
                .ToSelectList(c => c.ToString(), c => c.ToString());
            return Json(list, JsonRequestBehavior.AllowGet);
        }


        public ActionResult ExistsUser(string userName)
        {
            return Json(!_userPasswordTask.ExistsUser(userName), JsonRequestBehavior.AllowGet);
        }

        public ActionResult CanUpdate(string userName)
        {
            string errMsg;
            var isValid = _userInfoTask.CanUpdate(userName, out errMsg);
            return Json(new { result = isValid, message = errMsg }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetCardTypePrice(int userTypeId, string userName)
        {
            var userInfo = _userInfoTask.GetByUserName(userName);
            var userCardType = _cardTypeTask.GetById(userInfo.CardType);
            var cardType = _cardTypeTask.Get(userInfo.CardClass, userTypeId);

            return Json(cardType.Price - userCardType.Price, JsonRequestBehavior.AllowGet);
        }

    }
}